package com.attrisoft.sanger.aws;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;

public class S3Client {
    
    private static String bucket = System.getProperty("AwsBucket");
    private static String credentials = System.getProperty("AwsCredentials");
    
    public static void upload(String folder, String path, String fname) throws IOException {
        AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(new File(credentials)));
        s3.putObject(new PutObjectRequest(bucket, folder +"/" +fname, new File(path + java.io.File.separator +fname)));
    }
    
    public static List<FileInfo> getFiles(String folder) throws IOException {
        AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(new File(credentials)));
        ObjectListing objectListing = s3.listObjects(new ListObjectsRequest()
            .withBucketName(bucket)
            .withPrefix(folder));
        ArrayList<FileInfo> list = new ArrayList<FileInfo>();
        for (S3ObjectSummary os : objectListing.getObjectSummaries()) {
            if (os.getSize() > 0) {
                list.add(new FileInfo(os.getKey().substring(folder.length()+1), os.getSize(), os.getLastModified()));
            }
        }
        return list;
    }
    
    public static void delete(String folder, String fname) throws IOException {
        AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(new File(credentials)));
        s3.deleteObject(bucket, folder +"/" +fname);
    }
    
    public static InputStream get(String folder, String fname) throws IOException {
        AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(new File(credentials)));
        S3Object object = s3.getObject(new GetObjectRequest(bucket, folder +"/" +fname)); 
        return object.getObjectContent();
    }
    
    public static void main(String[] argv) throws Exception {
        for (FileInfo info : getFiles("david")) {
            System.err.println(info);
        }
    }
}
